package com.example.administrator.newxlmedical;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import adapters.CountSearchAdapter;
import adapters.CountSpinnerAdapter;
import adapters.LogAdapter;
import adapters.LogSearchUserAdapter;
import beans.CabinetInfoBean;
import beans.LogBean;
import beans.NewUserInfoBean;
import beans.UserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.DateDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.ActivityUtil;
import utils.FormateUtils;
import utils.LogSortUtils;
import utils.ObjectSaveUtil;
import utils.ScreenUtils;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.ViewUtil;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

public class LogActivity extends BaseActivity {

    @BindView(R.id.rv_log_activity)
    RecyclerView recyclerView;
    @BindView(R.id.sp_log_operate)
    Spinner spOperate;
    @BindView(R.id.tv_log_start_date)
    TextView tvStartDate;
    @BindView(R.id.tv_log_end_date)
    TextView tvEndDate;
    @BindView(R.id.et_log_user)
    EditText etUser;
    @BindView(R.id.tv_log_search)
    TextView tvSearch;
    @BindView(R.id.fl_log_empty)
    FrameLayout flEmpty;
    @BindView(R.id.iv_common_toolbar_home)
    ImageView ivHome;
    @BindView(R.id.tv_log_name)
    TextView tvName;
    @BindView(R.id.iv_log_name_sort)
    ImageView ivNameSort;
    @BindView(R.id.rl_log_name_sort1)
    RelativeLayout rlNameSort;
    @BindView(R.id.tv_log_cabinet)
    TextView tvCabinet;
    @BindView(R.id.iv_log_cabinet_sort)
    ImageView ivCabinetSort;
    @BindView(R.id.rl_log_cabinet_sort1)
    RelativeLayout rlCabinetSort;
    @BindView(R.id.tv_log_dept)
    TextView tvDept;
    @BindView(R.id.iv_log_dept_sort)
    ImageView ivDeptSort;
    @BindView(R.id.rl_log_dept_sort1)
    RelativeLayout rlDeptSort;
    @BindView(R.id.tv_log_role)
    TextView tvRole;
    @BindView(R.id.iv_log_role_sort)
    ImageView ivRoleSort;
    @BindView(R.id.rl_log_role_sort1)
    RelativeLayout rlRoleSort;
    @BindView(R.id.tv_log_time)
    TextView tvTime;
    @BindView(R.id.iv_log_time_sort)
    ImageView ivTimeSort;
    @BindView(R.id.rl_log_time_sort1)
    RelativeLayout rlTimeSort;
    @BindView(R.id.tv_operate)
    TextView tvOperate;
    @BindView(R.id.iv_log_operate_sort)
    ImageView ivOperateSort;
    @BindView(R.id.rl_log_operate_sort1)
    RelativeLayout rlOperateSort;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.iv_log_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_log_number_sort1)
    RelativeLayout rlNumberSort;
    @BindView(R.id.rv_log_user_search)
    RecyclerView rvUserSearch;
    //要查询的用户 id,等于0说明没有查询用户
    private String searchUserId = "0";
    private String userId;
    private boolean isNeedEmptyView = true;
    private StringBuilder sbUserIds = new StringBuilder();
    private StringBuilder sbCabinetInfoIds = new StringBuilder();

    //分页相关
    private int pageIndex = 1, pageSize = 100;
    //加载更多数据时最后一项的索引
    private int lastLoadDataItemPosition;
    //允许的最大的条目
//    private int maxSize = 500;

    private int netWorkCount;
    private LogAdapter adapter;
    private List<LogBean.LogDetailBean> list = new ArrayList<>();
    private List<LogBean.LogDetailBean> sortList = new ArrayList<>();
    private List<LogBean.LogDetailBean> commonList = new ArrayList<>();
    private List<UserInfoBean> userList = new ArrayList<>();
    private int roleInfoId;
    private NewUserInfoBean.DataBean userInfoBean;
    private int operaType;
    String startDate;
    String endDate;
    private String[] operaTypeInfo = {"全部", "验收", "放入", "取出", "使用"};
    private boolean isLoadingMore = true;
    private CountSpinnerAdapter spinnerAdapter;
    private boolean isSortName, isSortDept, isSortRole, isSortCabinet, isSortOperate, isSortNumber, isSortTime;
    private int sortName, sortDept, sortRole, sortCabinet, sortOperate, sortNumber, sortTime;
    private LogSearchUserAdapter searchAdapter;
    private boolean isSearch = true;
    private boolean isCkickBtn;
    private boolean isLoading = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log);
        ButterKnife.bind(this);
    }

    private void loadingTask() {
        sort(0);
        isLoadingMore = false;
        //护士和供应商只能查自己的日志
        if (roleInfoId == Constants.ROLE_NURSE || roleInfoId == Constants.ROLE_SUPPLIER) {
            //只能查询自己的日志
            if (!searchUserId.equals("0") && !searchUserId.equals(String.valueOf(userInfoBean.getID()))) {
                hideLoadingView();
                showEmptyView(flEmpty);
                ToastUtil.showToast(LogActivity.this, "您不能查询其他人的日志");
            } else {
                getLogs(String.valueOf(operaType), startDate, endDate, String.valueOf(userInfoBean.getID()), String.valueOf(pageIndex), String.valueOf(pageSize));
            }
        } else {
            getLogs(String.valueOf(operaType), startDate, endDate, searchUserId, String.valueOf(pageIndex), String.valueOf(pageSize));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initView() {
        super.initView();
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(LogActivity.this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        adapter = new LogAdapter(LogActivity.this, list);
        roleInfoId = userInfoBean.getRoleInfoId();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        recyclerView.setVisibility(View.GONE);
        spinnerAdapter = new CountSpinnerAdapter(LogActivity.this, R.layout.spinner_layout, operaTypeInfo);
        spOperate.setAdapter(spinnerAdapter);
        spinnerAdapter.setDropDownViewResource(R.layout.spinner_bg);

        LinearLayoutManager manager1 = new LinearLayoutManager(this);
        searchAdapter = new LogSearchUserAdapter(LogActivity.this, userList);
        rvUserSearch.setLayoutManager(manager1);
        rvUserSearch.setAdapter(searchAdapter);
        showLoadingView(flEmpty);
        loadingTask();
    }

    @Override
    protected void setListener() {

        spOperate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinnerAdapter.setSelectPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                LogBean.LogDetailBean logDetailBean = adapter.getList().get(postion);
                Intent intent = new Intent(LogActivity.this, LogDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.LOG_DETAIL_BUNDLE, logDetailBean);
                intent.putExtra(Constants.LOG_DETAIL, bundle);
                startActivity(intent);

            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE && lastLoadDataItemPosition == adapter.getItemCount()) {
                    if (isLoadingMore) {
                        pageIndex++;
                        isNeedEmptyView = false;
                        loadingTask();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    lastLoadDataItemPosition = lastVisibleItem + 1;
                }
            }
        });

        etUser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (isSearch) {
                    Log.e(TAG, "onTextChanged: ");
                    if (!TextUtils.isEmpty(s.toString())) {
                        rvUserSearch.setVisibility(View.VISIBLE);
                        String user = etUser.getText().toString();
                        getUserInfo("select * from UserInfo where Name like '%" + user + "%'", 2);
                    } else {
                        rvUserSearch.setVisibility(View.GONE);
                    }
                } else {
                    isSearch = true;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        searchAdapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String supplier = userList.get(position).getName();
                searchUserId = userList.get(position).getID() + "";
                Log.e(TAG, "onItemClick: " + searchUserId);
                isSearch = false;
                etUser.setText(supplier);
                rvUserSearch.setVisibility(View.GONE);
                etUser.setSelection(supplier.length());
                userList.clear();
            }
        });

    }

    @OnClick({R.id.tv_log_start_date, R.id.tv_log_end_date, R.id.tv_log_search, R.id.iv_common_toolbar_home, R.id.rl_log_operate_sort1,
            R.id.rl_log_name_sort1, R.id.rl_log_cabinet_sort1, R.id.rl_log_dept_sort1, R.id.rl_log_role_sort1, R.id.rl_log_time_sort1,
            R.id.rl_log_number_sort1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_log_start_date:
                new DateDialog(LogActivity.this, R.style.dialog, "开始时间", tvStartDate.getText().toString(), new DateDialog.OnClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String date) {
                        String nowTime = TimeUtil.getMillisecondDate();
                        if (TimeUtil.checkTime(date)) {
                            date = nowTime.substring(0, 10);
                        }
                        tvStartDate.setText(date);
                        dialog.cancel();
                    }
                }).show();
                break;
            case R.id.tv_log_end_date:
                new DateDialog(LogActivity.this, R.style.dialog, "结束时间", tvEndDate.getText().toString(), new DateDialog.OnClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String date) {
                        tvEndDate.setText(date);
                        dialog.cancel();
                    }
                }).show();
                break;
            case R.id.tv_log_search:
                search();
                break;
            case R.id.iv_common_toolbar_home:
                ActivityUtil.jumpToActivity(LogActivity.this, MainActivity.class);
                finish();
                break;
            case R.id.rl_log_name_sort1:
                sort(1);
                break;
            case R.id.rl_log_cabinet_sort1:
                Log.e(TAG, "onViewClicked: ");
                sort(2);
                break;
            case R.id.rl_log_dept_sort1:
                sort(3);
                break;
            case R.id.rl_log_role_sort1:
                sort(4);
                break;
            case R.id.rl_log_time_sort1:
                sort(5);
                break;
            case R.id.rl_log_operate_sort1:
                sort(6);
                break;
            case R.id.rl_log_number_sort1:
                sort(7);
                break;
        }
    }

    private void search() {
        recyclerView.scrollToPosition(0);
        adapter.setLoading(true);
        isCkickBtn = true;
        startDate = tvStartDate.getText().toString();
        endDate = tvEndDate.getText().toString();
        Log.e(TAG, "search: " + startDate + "   " + endDate);
        if (TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
            ToastUtil.showToast(this, "请选择开始时间!!!");
            isCkickBtn = false;
            return;
        }

        if (!TextUtils.isEmpty(startDate) && TextUtils.isEmpty(endDate)) {
            ToastUtil.showToast(this, "请选择结束时间!!!");
            isCkickBtn = false;
            return;
        }

        rvUserSearch.setVisibility(View.GONE);
        sort(0);

        ScreenUtils.closeKeybord(etUser, this);
        operaType = spOperate.getSelectedItemPosition();
        if (operaType != 0) {
            operaType += 1;
        }
        pageIndex = 1;
        list.clear();
        sortList.clear();
        commonList.clear();
//        adapter.notifyDataSetChanged();
        hideEmptyView();
        showLoadingView(flEmpty);
        isNeedEmptyView = true;
        String user = etUser.getText().toString();
        if (!TextUtils.isEmpty(user)) {
            getUserInfo("select * from UserInfo where Name = '" + user + "'", 3);
        } else {
            searchUserId = "0";
            loadingTask();
        }
    }

    private void getLogs(final String type, String startTime, String endTime, String userId, final String pageIndex, final String size) {
        isLoading = false;
        final Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type", type);
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            paramsMap.put("startTime", startTime + " 00:00:00.000");
            paramsMap.put("endTime", endTime + " 23:59:59.000");
        } else {
            paramsMap.put("startTime", "");
            paramsMap.put("endTime", "");
        }
        paramsMap.put("userId", userId);
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", size);
        paramsMap.put("deptCode", NetAddress.deptCode);

        new Thread(new Runnable() {
            @Override
            public void run() {

                GetRetrofit.getInstance().getLogs(NetAddress.token, NetAddress.machineCode, paramsMap).subscribeOn(Schedulers.io())
                        .groupBy(new Func1<LogBean, Boolean>() {
                            @Override
                            public Boolean call(LogBean logBean) {
                                return logBean.getLogDetail() == null ? false : logBean.getLogDetail().size() > 0;
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .flatMap(new Func1<GroupedObservable<Boolean, LogBean>, Observable<LogBean.LogDetailBean>>() {
                    @Override
                    public Observable<LogBean.LogDetailBean> call(GroupedObservable<Boolean, LogBean> booleanNewOperateLogBeanGroupedObservable) {
                        if (booleanNewOperateLogBeanGroupedObservable.getKey()) {
                            sbUserIds.delete(0, sbUserIds.length());
                            sbCabinetInfoIds.delete(0, sbCabinetInfoIds.length());
                            return booleanNewOperateLogBeanGroupedObservable
                                    .flatMap(new Func1<LogBean, Observable<LogBean.LogDetailBean>>() {
                                        @Override
                                        public Observable<LogBean.LogDetailBean> call(LogBean logBean) {
                                            return Observable.from(logBean.getLogDetail()).doOnNext(new Action1<LogBean.LogDetailBean>() {
                                                @Override
                                                public void call(LogBean.LogDetailBean logDetailBean) {
                                                    sbUserIds.append("'" + logDetailBean.getUserId() + "',");
                                                    if (sbCabinetInfoIds.toString().length() != String.valueOf(logDetailBean.getCabinetInfoId()).length() && !sbCabinetInfoIds.toString().contains(String.valueOf(logDetailBean.getCabinetInfoId()))) {
                                                        sbCabinetInfoIds.append("'" + logDetailBean.getCabinetInfoId() + "',");
                                                    }
                                                    list.add(logDetailBean);
                                                    sortList.add(logDetailBean);
                                                    commonList.add(logDetailBean);
                                                    logDetailBean.setOptionType(logDetailBean.getOptionType());
                                                    logDetailBean.setOperate(FormateUtils.getOperate(logDetailBean.getOptionType()));
                                                }
                                            }).last();
                                        }
                                    });
                        } else {
                            Log.e(TAG, "aaaa: " );
                            hideLoadingView();
                            isLoadingMore = false;
                            if (isNeedEmptyView && list.size() == 0) {
                                showEmptyView(flEmpty);
                            }else {
                                list.get(0).setLoadMore(true);
                                adapter.setLoading(false);
                            }
                            adapter.notifyDataSetChanged();
                            return null;
                        }
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<LogBean.LogDetailBean>() {
                    @Override
                    public void call(LogBean.LogDetailBean logDetailBean) {
                        Log.e(TAG, "call: " + list.size() + "  " + pageSize);
                        if (list.size() < pageSize) {
                            isLoadingMore = false;
                        } else {
                            isLoadingMore = true;
                        }
                        String userIds = sbUserIds.deleteCharAt(sbUserIds.length() - 1).toString();
                        getUserInfo("select Name,ID,Department,RoleInfoId from UserInfo where ID in (" + userIds + ")", 1);
                        String cabinetInfoIds = sbCabinetInfoIds.deleteCharAt(sbCabinetInfoIds.length() - 1).toString();
                        getCabinetNumber(cabinetInfoIds);
                    }
                }, new MyAction1() {
                    @Override
                    public void call(Throwable throwable) {
                        super.call(throwable);

                        hideLoadingView();
                        if (list.size() != 0) {
                            showEmptyView(flEmpty);
                        }
                    }
                });
            }
        }).start();
    }

    private void getUserInfo(final String sql, final int type) {
        isLoading = false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Call<ArrayList<UserInfoBean>> call = GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sql);
                call.enqueue(new Callback<ArrayList<UserInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                        ArrayList<UserInfoBean> body = response.body();
                        if (type == 1) {
                            if (body != null && body.size() > 0) {
                                UserInfoBean userInfoBean;
                                LogBean.LogDetailBean logDetailBean;
                                String[] roleType = FormateUtils.getRoleType();
                                int roleInfoId;
                                for (int i = 0; i < body.size(); i++) {
                                    userInfoBean = body.get(i);
                                    for (int m = 0; m < list.size(); m++) {
                                        logDetailBean = list.get(m);
                                        if (logDetailBean.getUserId() == userInfoBean.getID()) {
                                            logDetailBean.setName(userInfoBean.getName());
                                            logDetailBean.setDepartment(userInfoBean.getDepartment());
                                            roleInfoId = userInfoBean.getRoleInfoId();
                                            if (roleInfoId > 0 && roleInfoId <= roleType.length) {
                                                logDetailBean.setRoleInfo(roleType[roleInfoId - 1]);
                                            }
                                        }
                                    }
                                }
                                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                            } else {
                                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                            }
                        } else if (type == 2) {
                            if (TextUtils.isEmpty(etUser.getText().toString())) {
                                rvUserSearch.setVisibility(View.GONE);
                            }

                            if (body != null && body.size() > 0) {
                                rvUserSearch.setVisibility(View.VISIBLE);
                                UserInfoBean userInfoBean = body.get(0);
                                searchUserId = userInfoBean.getID() + "";
                                userList.clear();
                                userList.addAll(body);
                                searchAdapter.notifyDataSetChanged();
                            } else {
                                rvUserSearch.setVisibility(View.GONE);
                                searchUserId = "0";
                            }

                        } else {
                            if (body != null && body.size() > 0) {
                                Log.e(TAG, "onResponse: ");
                                UserInfoBean userInfoBean = body.get(0);
                                searchUserId = userInfoBean.getID() + "";
                                loadingTask();
                            } else {
                                searchUserId = "-1";
                                Log.e(TAG, "onResponse: null ");
                                hideLoadingView();
                                showEmptyView(flEmpty);
                            }
                        }
                        isLoading = true;
                    }

                    @Override
                    public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {

                    }
                });
            }
        }).start();
    }

    private void getCabinetNumber(final String cabinetInfoIds) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                GetRetrofit.getInstance().getCabinetInfoId(NetAddress.token, NetAddress.machineCode, "select * from CabinetInfo where ID in (" + cabinetInfoIds + ")")
                        .subscribeOn(Schedulers.io()).groupBy(new Func1<List<CabinetInfoBean>, Boolean>() {
                    @Override
                    public Boolean call(List<CabinetInfoBean> cabinetInfoBeen) {
                        return cabinetInfoBeen == null ? false : cabinetInfoBeen.size() > 0;
                    }
                }).flatMap(new Func1<GroupedObservable<Boolean, List<CabinetInfoBean>>, Observable<CabinetInfoBean>>() {
                    @Override
                    public Observable<CabinetInfoBean> call(GroupedObservable<Boolean, List<CabinetInfoBean>> booleanListGroupedObservable) {
                        if (booleanListGroupedObservable.getKey()) {
                            return booleanListGroupedObservable.flatMap(new Func1<List<CabinetInfoBean>, Observable<CabinetInfoBean>>() {
                                @Override
                                public Observable<CabinetInfoBean> call(List<CabinetInfoBean> cabinetInfoBeen) {
                                    return Observable.from(cabinetInfoBeen).doOnNext(new Action1<CabinetInfoBean>() {
                                        @Override
                                        public void call(CabinetInfoBean cabinetInfoBean) {
                                            LogBean.LogDetailBean logDetailBean;
                                            for (int m = 0; m < list.size(); m++) {
                                                logDetailBean = list.get(m);
                                                if (logDetailBean.getCabinetInfoId() == cabinetInfoBean.getID()) {
                                                    logDetailBean.setLogicNumber(cabinetInfoBean.getLogicNumber());
                                                }
                                            }
                                        }
                                    }).last();
                                }
                            });
                        } else {
                            isLoading = true;
                            sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                            return null;
                        }
                    }
                }).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<CabinetInfoBean>() {
                    @Override
                    public void call(CabinetInfoBean cabinetInfoBean) {
                        isLoading = true;
                        sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    }
                }, new MyAction1());
            }
        }).start();
    }

    @Override
    protected void onHandleMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.FINISH_NETWORK:
                netWorkCount++;
                if (netWorkCount == 2) {
                    netWorkCount = 0;
                    Log.e(TAG, "onHandleMessage: " + list.size());
                    hideLoadingView();
                    isCkickBtn = false;
                    if (list.size() < 100) {
                        adapter.setLoading(false);
                    }
                    adapter.notifyDataSetChanged();
                    recyclerView.setVisibility(View.VISIBLE);
                }
                break;

            case HandlerConstant.LOG_SORT_FINISH:

                adapter.setData(sortList);
                adapter.notifyDataSetChanged();

                Log.e(TAG, "finish: ");
                break;

        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortName != 2) {
                isSortName = !isSortName;
                sortName++;
                LogSortUtils.sortLogName(sortList, isSortName);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortName = 0;
            isSortName = false;
        }

        if (type == 2) { // 按柜号
            if (sortCabinet != 2) {
                isSortCabinet = !isSortCabinet;
                sortCabinet++;
                LogSortUtils.sortLogCabinet(sortList, isSortCabinet);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortCabinet = 0;
            isSortCabinet = false;
        }

        if (type == 3) {  //按科室
            if (sortDept != 2) {
                isSortDept = !isSortDept;
                sortDept++;
                LogSortUtils.sortLogDept(sortList, isSortDept);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortDept = 0;
            isSortDept = false;
        }

        if (type == 4) { // 角色
            if (sortRole != 2) {
                isSortRole = !isSortRole;
                sortRole++;
                LogSortUtils.sortLogRole(sortList, isSortRole);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortRole = 0;
            isSortRole = false;
        }

        if (type == 5) {
            if (sortTime != 2) {
                isSortTime = !isSortTime;
                sortTime++;
                LogSortUtils.sortLogTime(sortList, isSortTime);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortTime = 0;
            isSortTime = false;
        }

        if (type == 6) {
            if (sortOperate != 2) {
                isSortOperate = !isSortOperate;
                sortOperate++;
                LogSortUtils.sortLogOperate(sortList, isSortOperate);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortOperate = 0;
            isSortOperate = false;
        }

        if (type == 7) {
            if (sortNumber != 2) {
                isSortNumber = !isSortNumber;
                sortNumber++;
                LogSortUtils.sortLogNumber(sortList, isSortNumber);
            } else {
                clearSortDate();
                sortList.clear();
                sortList.addAll(commonList);
            }
        } else {
            sortNumber = 0;
            isSortNumber = false;
        }
        ViewUtil.setSortColor(this, tvCabinet, ivCabinetSort, sortCabinet);
        ViewUtil.setSortColor(this, tvName, ivNameSort, sortName);
        ViewUtil.setSortColor(this, tvDept, ivDeptSort, sortDept);
        ViewUtil.setSortColor(this, tvRole, ivRoleSort, sortRole);
        ViewUtil.setSortColor(this, tvTime, ivTimeSort, sortTime);
        ViewUtil.setSortColor(this, tvOperate, ivOperateSort, sortOperate);
        ViewUtil.setSortColor(this, tvNumber, ivNumberSort, sortNumber);

        if (type != 0) {
            adapter.setData(sortList);
            adapter.notifyDataSetChanged();
        }
    }

    private void clearSortDate() {
        sortName = 0;
        sortDept = 0;
        sortRole = 0;
        sortCabinet = 0;
        sortTime = 0;
        sortNumber = 0;
        sortOperate = 0;
    }
}
